﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ls.Utils;
using Ls.Web.Api.Models;
using Ls.Web.Framework;
using Ls.Web.Framework.Permissions;
using Microsoft.AspNetCore.Mvc;

namespace Ls.Web.Api.Controllers
{
    /// <summary>
    /// 调拨单接口
    /// </summary>
    public class OrderController : BaseController
    {
        private WhOrderService whOrderService = new WhOrderService();
        /// <summary>
        /// 调入扫描的单据列表
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// 返回值：
        /// 
        ///       {
        ///           "resultCode": "状态",
        ///           "data": [
        ///               {
        ///                   "id": 调拨单Id,
        ///                   "code": "调拨单编号",
        ///                   "outWhId": 调出仓库Id,
        ///                   "outWhName": "调出仓库名",
        ///                   "outTime": "调出时间"
        ///               }
        ///           ]
        ///       }
        /// </remarks>
        [HttpPost]
        [Route("/order/preinlist")]
        [Permission("App.Order.PreInList")]
        public IActionResult PreInList()
        {
            var dataList = whOrderService.GetPreInList(this.UserId);
            return GetSuccessResult(dataList);
        }

        /// <summary>
        /// 调出扫描的单据列表
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// 返回值：
        /// 
        ///       {
        ///           "resultCode": "状态",
        ///           "data": [
        ///               {
        ///                   "id": 调拨单Id,
        ///                   "code": "调拨单编号",
        ///                   "inWhId": 调入仓库Id,
        ///                   "inWhName": "调入仓库名",
        ///                   "outTime": "调出时间"
        ///               }
        ///           ]
        ///       }
        /// </remarks>
        [HttpPost]
        [Route("/order/preoutlist")]
        [Permission("App.Order.PreOutList")]
        public IActionResult PreOutList()
        { 
            var dataList = whOrderService.GetPreOutList(this.UserId);
            return GetSuccessResult( dataList);
        }

        /// <summary>
        /// 调拨单详情
        /// </summary>
        /// <param name="id">调拨单Id</param>
        /// <returns></returns>
        /// <remarks>
        /// 返回值：
        /// 
        ///         {
        ///             "resultCode": "返回状态",
        ///             "data": {
        ///                 "productBarcodes": "车辆16位编码以\n分割",
        ///                 "batteries": [
        ///                     {
        ///                         "code": "电池编码",
        ///                         "name": "电池名称",
        ///                         "spec": "电池型号",
        ///                         "amount": 数量
        ///                     } 
        ///                 ]
        ///             }
        ///         }
        /// </remarks>
        [HttpPost]
        [Route("/order/preinfo")]
        [Permission("App.Order.PreInfo")]
        public IActionResult OrderInfo(long  id) {
            dynamic data = whOrderService.Single("who_code,who_status,wh_id_out,wh_id_in,product_barcodes_out", new { who_id = id });
            if (data == null)
            {
                return GetErrorResult("数据不存在");
            }
            if (data.who_status != 1)
            {
                return GetErrorResult("当前状态的单据不允许操作");
            }

            string ProductBarcodes = data.product_barcodes_out; // 调出的整车16位编码
            string detailSql = @"select battery_code as code,battery_name as name,battery_spec as spec,sum(battery_amount) as amount
                                 from wh_order_detail 
                                 where  who_id=@who_id  and battery_code is not null and battery_code !='' 
                                 group by  battery_code ,battery_name,battery_spec";
            List<dynamic> dataList = whOrderService.db.Sql(detailSql)
                .Parameter("who_id", id)
                .QueryMany<dynamic>();
            return GetSuccessResult(new   { productBarcodes = ProductBarcodes, batteries = dataList });
        }

        /// <summary>
        /// 调入确认
        /// </summary>
        /// <param name="id">调拨单Id</param> 
        /// <param name="codes">扫描条码</param> 
        /// <returns></returns>
        [HttpPost]
        [Route("/order/bringin")]
        [Permission("App.Order.BringIn")]
        public IActionResult BringIn(long id, string codes)
        {
            var data = whOrderService.Single(@"who_id, who_code, who_status, wh_id_out, who_out_time, wh_id_in, who_in_time, create_id, create_time, update_id, update_time,product_barcodes_out,product_barcodes_in", new { who_id = id });
            wh_order model = JsonHelper.ToObject<wh_order>(JsonHelper.ToJson(data));
            string product_barcodes_out = model.product_barcodes_out;

            if (this.WhId != model.wh_id_in) {
                return GetErrorResult("调入仓库与门店仓库不一致！");
            }

            string[] arr1 = codes.Trim().Split('\r', '\n');
            string[] arr2 = product_barcodes_out.Trim().Split('\r', '\n');

            for (int i = 0; i < arr1.Length; i++) {
                bool isHave = false;
                for (int ii = 0; ii < arr2.Length; ii++) {
                    if (arr2[ii] == arr1[i]) {
                        isHave = true;
                        break;
                    }
                }
                if (!isHave) {
                    return GetErrorResult("扫入的条码 "+ arr1[i] +" 在调出条码中不存在！");
                }
            }

            int result = whOrderService.BringIn(model);
            if (result > 0) {
                return GetSuccessResult();
            }
            return GetErrorResult();
        }

        /// <summary>
        /// 调出确认
        /// </summary>
        /// <param name="id">调拨单Id</param> 
        /// <param name="codes">扫描条码</param> 
        /// <returns></returns>
        [HttpPost]
        [Route("/order/bringout")]
        [Permission("App.Order.BringOut")]
        public IActionResult BringOut(long id, string codes)
        {
            var data = whOrderService.Single(@"who_id, who_code, who_status, wh_id_out, who_out_time, wh_id_in, who_in_time, create_id, create_time, update_id, update_time,product_barcodes_out,product_barcodes_in", new { who_id = id });
            wh_order model = JsonHelper.ToObject<wh_order>(JsonHelper.ToJson(data));
            string product_barcodes_out = model.product_barcodes_out;

            if (this.WhId != model.wh_id_out) {
                return GetErrorResult("调出仓库与门店仓库不一致！");
            }

            string[] arr1 = codes.Trim().Split('\r', '\n');
            string[] arr2 = product_barcodes_out.Trim().Split('\r', '\n');

            for (int i = 0; i < arr1.Length; i++)
            {
                bool isHave = false;
                for (int ii = 0; ii < arr2.Length; ii++)
                {
                    if (arr2[ii] == arr1[i])
                    {
                        isHave = true;
                        break;
                    }
                }
                if (!isHave)
                {
                    return GetErrorResult("扫入的条码 " + arr1[i] + " 在调出条码中不存在！");
                }
            }

            int result = whOrderService.BringIn(model);
            if (result > 0)
            {
                return GetSuccessResult();
            }
            return GetErrorResult();
        }
    }
}